<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Utils\ResponseFactory;
use App\Http\Requests\user\ChangeUserPwdRequest;
use App\Http\Requests\user\ChangeUserRequest;
use App\Http\Requests\user\SendEmailRequest;
use App\Http\Requests\user\UserLoginRequest;
use App\Http\Requests\user\UserRegisterRequest;
use App\Models\Manager\Group;
use App\Models\Manager\GroupManager;

use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use PhpParser\Node\Stmt\Foreach_;


/**
 *
 */
class UserController extends Controller
{
    //

    /**
     * 用户登录
     * @param UserLoginRequest $request
     * @return JsonResponse
     */
    public function login(UserLoginRequest $request): JsonResponse
    {
        $message = $request->validated();
        if (!captcha_api_check($message["code"], $message["key"])) {
            return ResponseFactory::simpleResponse(false, "验证码错误", 412);
        }

        if (!$token = auth('api')->attempt($request->only(['userName', 'password']))) {
            return ResponseFactory::simpleResponse(false, "账号密码错误", 401);
        }
        return ResponseFactory::customResponse(["token" => $token]);

    }

    /**
     * 用户注册
     * @param UserRegisterRequest $request
     * @return JsonResponse
     */
    public function register(UserRegisterRequest $request): JsonResponse
    {
        $message = $request->validated();
        if (session("EmailCode") === $message["EmailCode"]) {
            if (User::all()->where("userName", $message["userName"])->first()) {
                return ResponseFactory::simpleResponse(false, "用户名已存在", 412);
            }
            if (User::all()->where("email", $message["email"])->first()) {
                return ResponseFactory::simpleResponse(false, "邮箱已被注册", 412);
            }
            if ($request->has('tel') && User::all()->where("tel", $message["tel"])->first()) {
                return ResponseFactory::simpleResponse(false, "手机号已被注册", 412);
            }

            $userMessae = [
                'userName' => $message["userName"],
                'password' => Hash::make($message["password"]),
                'email' => $message["email"],
            ];
            if (!$request->has('nickName')) {
                $userMessae['nickName'] = $message['userName'];
            } else {
                $userMessae['nickName'] = $message["nickName"];
            }
            if ($request->has('tel')) {
                $userMessae['tel'] = $message['tel'];
            }


            $user = User::create($userMessae);

            //初始化用户组
            $groupMessage = [
                'name' => $message["userName"],
                'description' => '默认用户组'
            ];
            //$group = Group::create($groupMessage);
            $group = User::find($user['id'])->Group()->create($groupMessage);
            //配置组的创建者
            $manager = new GroupManager();
            $manager['roleId'] = Config::get('normalconfig.group.managerrole.creater');
            $manager['userId'] = $user['id'];
            $group->GroupManager()->save($manager);
            //初始化用户权限
            {
                $UserPermissions = [];
                $defaultUserPermission = Config::get('defaultpermission.user');
                foreach ($defaultUserPermission as $key => $value) {
                    $UserPermissions[] = [
                        "userId" => $user['id'],
                        "permissionId" => $value
                    ];
                }
                DB::table('users_permissions')->insert($UserPermissions);
            }
            //初始化组权限
            {
                $groupPermissions = [];
                $defaultGroupPermission = Config::get('defaultpermission.group');
                foreach ($defaultGroupPermission as $value) {
                    $groupPermissions[] = [
                        'groupId' => $group['id'],
                        'permissionId' => $value
                    ];
                }
                DB::table('group_permission_relation')->insert($groupPermissions);
            }
            //登录注册成功后删除session中保留的邮箱验证码
            session()->forget("EmailCode");
            return ResponseFactory::simpleResponse(true, "操作成功");
        } else {
            return ResponseFactory::simpleResponse(false, "验证码错误", 403);
        }

    }


    /**
     * logout
     * @return JsonResponse
     */
    public function logout(): JsonResponse
    {
        auth('api')->logout();
        return ResponseFactory::simpleResponse(true);
    }

    /** change User password and return new token
     * @param ChangeUserPwdRequest $request
     * @return JsonResponse
     */
    public function resetPasswd(ChangeUserPwdRequest $request)
    {
        if ($request->input('oldPwd') === $request->input('newPwd')) {
            return ResponseFactory::simpleResponse(false, "The new password and the old password cannot be the same", 403);
        }
        $userId = auth()->user()->id;
        $userName = auth()->user()->userName;
        if (!is_null($user = User::all()->find($userId))) {
            $password = $user->makeVisible('password')['password'];
            if (Hash::check($request->input('oldPwd'), $password)) {
                $result = DB::table('users')->where('id', $userId)->update([
                    'password' => Hash::make($request->input('newPwd'))
                ]);
                auth('api')->logout();
                if (!$token = auth('api')->attempt([
                    'userName' => $userName,
                    'password' => $request->input('newPwd')
                ])) {
                    return ResponseFactory::simpleResponse($result > 0, "The password was changed but can not get token", 500);
                }
                return ResponseFactory::customResponse([
                    'ref_token' => $token
                ]);
            } else {
                return ResponseFactory::simpleResponse(false, "The origin password is not right", 403);
            }
        }
        return ResponseFactory::simpleResponse(false, "This user is not exit", 403);
    }


    /**
     * Get User Message
     * @return JsonResponse
     */
    function GetUserMessage(): JsonResponse
    {
        $userId = auth()->user()->id;
        $user = User::all()->find($userId);
        return ResponseFactory::responseData($user);
    }


    /** change user message
     * @param ChangeUserRequest $request
     * @return JsonResponse
     */
    public function changeUserMessage(ChangeUserRequest $request): JsonResponse
    {
        $params = $request->all('nickName', 'tel', 'age', 'signature');
        $userId = auth()->user()->id;
        foreach ($params as $key => $value) {
            if ($value === null) {
                unset($params[$key]);
            }
        }
        if (count($params) === 0) {
            return ResponseFactory::simpleResponse(false, "you don't input any effective values", 412);
        }
        $user = User::find($userId);
        if (is_null($user)) {
            return ResponseFactory::simpleResponse(false, "this user is not exit", 401);
        }
        $result = $user->update($params);
        return ResponseFactory::simpleResponse(!is_null($result));
    }


    /**
     * 发送邮件
     * @param SendEmailRequest $request
     * @return JsonResponse
     */
    public function sendEmail(SendEmailRequest $request): JsonResponse
    {
        $formData = $request->validated();
//        生成邮箱验证码
        $code = random_int(1000, 9999);
//        存储Session值
        session(['EmailCode' => strval($code)]);
        Mail::send("email.EmailTemplate", ['targetEmail' => $formData['targetEmail'], 'code' => $code], function ($message) use ($formData) {
            $to = $formData["targetEmail"];
            $message->to($to)->subject("验证码");
        });
        $failures = Mail::failures();
        if ($failures != null) {
            foreach ($failures as $failure) {
                return ResponseFactory::simpleResponse(false, $failure, 500);
            }
        }
        return ResponseFactory::simpleResponse(true, "发送成功");
    }

    /**
     *
     * 登录获取验证码
     * @return JsonResponse
     */
    public function captcha(): JsonResponse
    {
        return ResponseFactory::customResponse([
            'url' => app('captcha')->create('default', true)
        ]);
    }

    public function CheckToken(): JsonResponse
    {
        return ResponseFactory::simpleResponse(true);
    }
}
